package com.lamer.console.blog.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lamer.console.blog.entity.Author;
import com.lamer.console.blog.service.IAuthorService;
import com.lamer.console.common.api.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 黄诗鹏
 * @since 2021-09-25
 */
@RestController
@RequestMapping("/blog")
public class AuthorController {

    @Autowired
    private IAuthorService authorService;

    @GetMapping("/author/page/")
    public ApiResult<Page<Author>> getPage(@RequestParam("search") String search) {
        JSONObject jsonObject = JSON.parseObject(search);
        Integer number = jsonObject.getInteger("page_number");
        Integer size = jsonObject.getInteger("page_size");
        String authorName = jsonObject.getString("authorName");

        LambdaQueryWrapper<Author> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(authorName)) queryWrapper.like(Author::getAuthorName, authorName);

        Page<Author> page = authorService.page(new Page<>(number, size), queryWrapper);
        return ApiResult.success(page);
    }

    @GetMapping("/author/{id}")
    public ApiResult<Author> getData(@PathVariable("id") int id) {
        Author data = authorService.getById(id);
        return data == null ? ApiResult.failed() : ApiResult.success(data);
    }

    @PostMapping("/author/")
    public ApiResult<String> insertData(@RequestBody Author data) {
        boolean flag = authorService.save(data);
        return flag ? ApiResult.success() : ApiResult.failed();
    }

    @PutMapping("/author/")
    public ApiResult<String> updateData(@RequestBody Author data) {
        boolean flag = authorService.updateById(data);
        return flag ? ApiResult.success() : ApiResult.failed();
    }

    @DeleteMapping("/author/list/")
    public ApiResult<String> deleteData(@RequestParam("ids") int[] ids) {
        List<Integer> collect = Arrays.stream(ids).boxed().collect(Collectors.toList());
        boolean flag = authorService.removeByIds(collect);
        return flag ? ApiResult.success() : ApiResult.failed();
    }

    @GetMapping("/author/list/")
    public ApiResult<List<Author>> getAuthorList() {
        List<Author> list = authorService.list();
        return ApiResult.success(list);
    }


}

